const https = require('https')
const fs = require('fs')
const path = require('path')

const express = require('express')
const cors = require('cors')
const expressjwt = require('express-jwt')

const config = require('./config.js')

const { errMessage, reqLog, resLog, tokenLog } = require('./router_handler/middleware.js')
const { initWebSocketServer } = require('./websocket/index.js')

const app = express()


// 中间件

// 允许的前端源
const allowedOrigins = ['http://localhost:8081', 'null', 'undefined']
app.use(cors({
    origin: (origin, callback) => {
        // 检查请求源是否在允许列表中
        if (allowedOrigins.includes(origin) || !origin) {
            callback(null, true); // 允许跨域
        } else {
            callback(new Error(`不允许的跨域请求: ${origin}`)) // 拒绝跨域
        }
    },
    credentials: true, // 允许携带凭证（关键）
    methods: ['GET', 'POST', 'OPTIONS'], // 允许的请求方法
    allowedHeaders: ['Content-Type', 'Authorization'] // 允许的请求头
})) // 跨域
app.use(express.json()) // json请求体
app.use(express.urlencoded({ extended: false })) // 解析表单


// app.use(resLog) // 打印日志
app.use(errMessage)
app.use(expressjwt({
    secret: config.jwtSecretKey,
    algorithms: ['HS256']
}).unless({ path: [/^\/api/, /^\/avatar/, /^\/$/] }))
// app.use(reqLog) // 打印日志

app.get('/', (req, res) => {
    res.send('hello world!')
})

// 配置静态资源
app.use(express.static(path.join(__dirname, 'data')))
// 配置路由
const userRouter = require('./router/user.js')
const userInfoRouter = require('./router/userInfo.js')
const friendsRouter = require('./router/friends.js')
// const sseRouter = require('./router/sse.js')
app.use('/api', userRouter)
app.use('/serv/userinfo', userInfoRouter)
app.use('/serv/friends', friendsRouter)
// app.use('/sse', sseRouter)

// 错误处理
app.use((err, req, res, next) => {
    // token异常
    if (err.name === 'UnauthorizedError') {
        // tokenLog(req, res)
        return res.cc('token身份认证失败', 20)
    }
    res.send({ code: -1, msg: '未知错误' })
    console.log('未知错误:', err.message)

})

// 加载SSL证书和私钥
const options = {
    key: fs.readFileSync(path.join(__dirname, 'private-key.pem')), // 私钥路径
    cert: fs.readFileSync(path.join(__dirname, 'certificate.pem')) // 证书路径
};

const server = https.createServer(options, app)
// 初始化 WebSocket 服务
const webSocketService = initWebSocketServer(server)

// 启动服务器
server.listen(config.port, () => {
    console.log(`Server running at https://127.0.0.1:${config.port}`)
})
server.timeout = config.timeout // 超时时间